const TronWeb = require('tronweb');
const fs = require('fs');
const path = require('path');

const config = require('./tronbox.js');
const shastaConfig = config.networks.shasta;
const contractData = JSON.parse(fs.readFileSync(path.join(__dirname, 'build/contracts/TRXBetLottery.json'), 'utf8'));

async function deploy() {
    console.log('🚀 开始部署合约...\n');
    
    const tronWeb = new TronWeb({ fullHost: shastaConfig.fullHost });
    
    // 检查连接
    const connected = await tronWeb.isConnected();
    if (!connected.fullNode) throw new Error('网络连接失败');
    console.log('✅ 网络连接正常\n');
    
    // 设置账户
    tronWeb.setPrivateKey(shastaConfig.privateKey);
    const account = tronWeb.defaultAddress.base58;
    const balance = await tronWeb.trx.getBalance(account);
    console.log(`账户: ${account}`);
    console.log(`余额: ${(balance / 1e6).toFixed(2)} TRX\n`);
    
    if (balance < 10000000) throw new Error('余额不足');
    
    // 准备参数
    const devWalletHex = tronWeb.address.toHex(account);
    const firstDeadline = Math.floor(Date.now() / 1000) + 3600;
    
    console.log(`开发地址: ${account}`);
    console.log(`截止时间: ${new Date(firstDeadline * 1000).toLocaleString()}\n`);
    
    // 获取并准备 bytecode
    let bytecode = contractData.bytecode;
    if (bytecode.startsWith('0x')) bytecode = bytecode.slice(2);
    
    // 编码构造函数参数
    const parameter = tronWeb.utils.abi.encodeParams(
        ['address', 'uint256'],
        [devWalletHex, firstDeadline.toString()]
    );
    const paramHex = parameter.startsWith('0x') ? parameter.slice(2) : parameter;
    
    // 完整的合约代码 = bytecode + 构造函数参数
    const contractCode = bytecode + paramHex;
    
    console.log(`Bytecode: ${bytecode.length / 2} bytes`);
    console.log(`参数: ${paramHex.length / 2} bytes`);
    console.log(`总计: ${contractCode.length / 2} bytes\n`);
    
    console.log('创建部署交易...');
    
    try {
        // 方法：创建修改后的 ABI（移除构造函数），然后使用完整 bytecode
        const abiWithoutConstructor = contractData.abi.filter(item => item.type !== 'constructor');
        
        // 使用 createSmartContract，传递修改后的 ABI 和完整 bytecode
        const tx = await tronWeb.transactionBuilder.createSmartContract({
            abi: abiWithoutConstructor,  // 没有构造函数的 ABI
            bytecode: contractCode  // 完整的 bytecode（已包含构造函数参数）
        }, account);
        
        // 设置交易参数
        tx.feeLimit = shastaConfig.feeLimit;
        
        console.log('签名交易...');
        const signed = await tronWeb.trx.sign(tx);
        
        console.log('广播交易...');
        const result = await tronWeb.trx.sendRawTransaction(signed);
        
        // 获取交易哈希（可能是对象或字符串）
        const txHash = typeof result === 'string' ? result : (result.txid || result.hash || JSON.stringify(result));
        
        console.log(`\n✅ 交易已提交！`);
        console.log(`交易哈希: ${txHash}\n`);
        console.log('等待确认（最多60秒）...');
        
        // 等待确认
        for (let i = 0; i < 30; i++) {
            await new Promise(r => setTimeout(r, 2000));
            
            try {
                const info = await tronWeb.trx.getTransactionInfo(txHash);
                
                if (info?.receipt?.result === 'SUCCESS') {
                    if (info.contract_address) {
                        const addr = tronWeb.address.fromHex(info.contract_address);
                        console.log(`\n🎉 部署成功！\n`);
                        console.log(`合约地址: ${addr}`);
                        console.log(`区块号: ${info.blockNumber}`);
                        console.log(`\n查看合约: https://shasta.tronscan.org/#/contract/${addr}`);
                        console.log(`查看交易: https://shasta.tronscan.org/#/transaction/${txHash}`);
                        return;
                    }
                } else if (info?.receipt?.result === 'REVERT') {
                    throw new Error(`交易失败: ${info.receipt.result}`);
                }
            } catch (err) {
                if (err.message && !err.message.includes('not found')) {
                    throw err;
                }
            }
            
            process.stdout.write(`  等待中... (${i + 1}/30)\r`);
        }
        
        throw new Error('确认超时，请查看交易状态');
        
    } catch (error) {
        console.error(`\n❌ 部署失败: ${error.message || error}`);
        if (error.stack) console.error(error.stack);
        throw error;
    }
}

deploy().catch(e => {
    console.error('错误:', e);
    process.exit(1);
});

